package com.example.basecomponent.cityPicker;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import com.example.basecomponent.cityPicker.model.City;
import com.github.promeg.pinyinhelper.Pinyin;
import com.github.promeg.tinypinyin.lexicons.android.cncity.CnCityDict;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsonParseUtil {

    public String getJson(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private ArrayList<City> mCities = new ArrayList<>();

    public List<City> getAllCities(Context context) {
        Pinyin.init(Pinyin.newConfig().with(CnCityDict.getInstance(context)));
        Gson gson = new Gson();
        String cityJson = getJson(context, "city.json");
        List<City> cities = gson.fromJson(cityJson, new TypeToken<List<City>>() {
        }.getType());
        for(City city:cities) {
            city.setPinyin(Pinyin.toPinyin(city.getName(),""));
        }
        mCities.addAll(cities);
        CityComparator comparator = new CityComparator();
        Collections.sort(mCities, comparator);
        Log.d("TAG", mCities.toString());
        return mCities;
    }

    public List<City> searchCity(String keyword) {
        List<City> results = new ArrayList<>();
        Pattern pattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
        for (int i = 0; i < mCities.size(); i++) {
            Matcher matcher;
            if (Pinyin.isChinese(keyword.charAt(0))) {
                matcher = pattern.matcher(mCities.get(i).getName());
            } else matcher = pattern.matcher(mCities.get(i).getPinyin());
            if (matcher.find()) {
                results.add(mCities.get(i));
            }
        }
        return results;
    }

    /**
     * sort by a-z
     */
    private class CityComparator implements Comparator<City> {
        @Override
        public int compare(City lhs, City rhs) {
            String a = lhs.getPinyin().substring(0, 1);
            String b = rhs.getPinyin().substring(0, 1);
            return a.compareTo(b);
        }
    }
}




















